package com.vitas.coin.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DB_NAME = "menu.db";

    private static final int VERSION = 4;

    private final String CREATE_DOWN = "CREATE TABLE IF NOT EXISTS down (id integer primary key autoincrement, uid integer, path text, time integer)";

    public static final String CREATE_LIST = "CREATE TABLE IF NOT EXISTS '%s' (id integer primary key autoincrement, uid integer, info text, time integer)";

    private final String CREATE_TYPE = "CREATE TABLE IF NOT EXISTS type (id integer primary key autoincrement,name text, uid text, time integer)";

    private final String CREATE_PLAY = "CREATE TABLE IF NOT EXISTS play (id integer primary key autoincrement,uid integer, info text, time integer, num integer default 1)";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_DOWN);
        db.execSQL(CREATE_TYPE);
        db.execSQL(CREATE_PLAY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        switch (oldVersion) {
            case 2:
                db.execSQL(CREATE_PLAY);
            case 3:
                addNum2Play(db);
        }
    }

    private void addNum2Play(SQLiteDatabase db) {
        if (isColumnExist(db, "play", "num")) {
            return;
        }
        try {
            db.execSQL("ALTER TABLE play ADD COLUMN num integer default 1");
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public final boolean isColumnExist(SQLiteDatabase db, String table, String column) {
        Cursor cursor = null;
        try {
            String sql = "select " + column + " from " + table + " limit 0,1";
            cursor = db.rawQuery(sql, null);
            return true;
        } catch (Throwable e) {
            return false;
        } finally {
            close(cursor);
        }
    }

    public final void close(Cursor c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (Throwable e) {

        }
    }
}
